package com.luo.d3s.light.mybatis.ec.domain.specification;

import com.luo.d3s.core.domain.service.specifcation.AbstractSpecification;
import com.luo.d3s.core.util.validation.Validates;
import com.luo.d3s.light.mybatis.ec.domain.category.Category;
import com.luo.d3s.light.mybatis.ec.domain.category.CategoryRepository;

import java.util.Optional;

/**
 * 分类验证规则
 *
 * @author luohq
 * @date 2023-01-05 8:47
 */
public class CategorySpecification extends AbstractSpecification<Category> {

    private CategoryRepository categoryRepository;

    public CategorySpecification(CategoryRepository categoryRepository) {
        this.categoryRepository = categoryRepository;
    }

    @Override
    public boolean isSatisfiedBy(Category category) {
        //验证分类名称唯一性
        //新增时（category.id为空）无需排除分类ID
        //修改时（category.id非空）需排除当前被修改的分类ID，即无需与自身分类名称进行比较
        Boolean existCategoryName = this.categoryRepository.existCategoryName(category.getCategoryName(), category.getId());
        Validates.isFalse(existCategoryName, "category name is repeated");

        //验证上级分类ID存在
        Optional.ofNullable(category.getParentCategoryId())
                .ifPresent(parentCategoryId -> {
                    CategoryExistSpecification categoryExistSpecification = new CategoryExistSpecification(this.categoryRepository);
                    categoryExistSpecification.isSatisfiedBy(parentCategoryId);
                });
        return true;
    }
}
